package org.jmetrix.et;

import org.aspectj.lang.ProceedingJoinPoint;
import org.jmetrix.bus.Bus;
import org.jmetrix.bus.impl.NamedBusFactory;
import org.jmetrix.group.GroupAspect;

/**
 * @author Konstantin Kuzmin
 * @version $Revision$
 * @since 01.10.11
 */
//TODO abstract from AspectJ
//TODO add debug logging
public abstract class ExecutionTimeAspect extends GroupAspect {

    private Bus bus;

    protected ExecutionTimeAspect() {
        bus = NamedBusFactory.getDefaultBus();
    }

    @Override
    protected String getGroup(final ProceedingJoinPoint pjp) {
        return pjp.getClass().getName();
    }

    @Override
    protected Object proceed(final ProceedingJoinPoint pjp) throws Throwable {
        //TODO more certain timing source
        final long startTime = System.currentTimeMillis();
        try {
            return pjp.proceed();
        } finally {
            final long executionTime = (System.currentTimeMillis() - startTime);
            sendEvent(executionTime);
        }
    }

    protected void sendEvent(final long executionTime) {
        final ExecutionTime executionTimeMetric = new ExecutionTime(executionTime);
        getBus().publish(executionTimeMetric);
    }

    private Bus getBus() {
        return bus;
    }
}
